from parse import runParse


code = []
global cur_line

def genExp(parseTree):
    if parseTree.nodeKind == 'num':
        code.append('push ' + parseTree.attr)
    elif parseTree.nodeKind == 'id':
        code.append('push ' + parseTree.attr)
    elif parseTree.nodeKind == 'op':  # 后序遍历生成逆波兰表达式
        ltree = parseTree.child[0]  # 左子树
        rtree = parseTree.child[1]  # 右子树
        cGen(ltree)
        cGen(rtree)
        code.append(parseTree.attr)



def genStmt(parseTree):
    # if-stmt -> if exp then stmt-sequence end
    #           |if exp then stmt-sequence else stmt-sequence end
    if parseTree.nodeKind == 'if':
        p1 = parseTree.child[0]  # test
        p2 = parseTree.child[1]  # then
        p3 = parseTree.child[2]  # else

        cGen(p1)
        code.append("jz Lable")  # 为0则执行else部分
        cGen(p2)

        code.append("Lable:")
        cGen(p3)

        pass
    elif parseTree.nodeKind == 'repeat':
        # repeat-stmt -> repeat stmt-sequence until exp
        p1 = parseTree.child[0]  # stmt-sequence
        p2 = parseTree.child[1]  # exp

        code.append("Lable1:")
        cGen(p1)
        cGen(p2)
        code.append("jz Lable1")
        pass
    elif parseTree.nodeKind == 'assign':
        p1 = parseTree.child[0]  # exp
        id = parseTree.attr  # id

        cGen(p1)
        code.append('pop ' + id)
    elif parseTree.nodeKind == 'read':
        code.append(f'readint "Input: "')
        code.append(f'pop {parseTree.attr}')
    elif parseTree.nodeKind == 'write':
        code.append(f'print "out is %d"')
    pass


def cGen(parseTree):  # 主循环   尾递归，可以改写成循环
    if parseTree is not None:
        if parseTree.kind == 'stmt':
            genStmt(parseTree)
        elif parseTree.kind == 'exp':
            genExp(parseTree)
        cGen(parseTree.sibling)


if __name__ == '__main__':
    parseTree = runParse()
    cGen(parseTree)
    fp = open('new.asm', 'w')
    fp.write("var x,fact\n")
    for i in code:
        fp.write(i + "\n")
